package com.bba.fms.common.ezspecial.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bba.fms.common.ezspecial.enums.Regular;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: fms
 * @Author: 王志鹏
 * @CreateTime: 2019-10-14 14:40
 * @description: 转型尝试
 */

@Slf4j
public class ConvertUtil {
    private ConvertUtil() {
    }

    public static Object tryToConvert(Type type, String v, String s) throws ParseException {
        if (type == String.class) {
            return v;
        } else if (int.class == type) {
            return Double.valueOf(v).intValue();
        } else if (long.class == type) {
            return Long.parseLong(v);
        } else if (double.class == type) {
            return Double.parseDouble(v);
        } else if (Double.class == type) {
            return Double.valueOf(v);
        } else if (Integer.class == type) {
            return Integer.valueOf(v);
        } else if (Long.class == type) {
            return Long.valueOf(v);
        } else if (Date.class == type) {
            if (VerifyUtil.checkByRegular(Regular.DATE.getRule(), v)) {
                return new SimpleDateFormat("yyyy-MM-dd").parse(v);

            } else if (VerifyUtil.checkByRegular(Regular.TIME.getRule(), v)) {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(v);
            } else {
                throw new RuntimeException(String.format("Try to Date Convert fail coloum is {%s} , value is {%s}!", s, v));
            }
        } else {
            throw new RuntimeException(String.format("Try to Convert fail coloum is {%s}, value is {%s} !", s, v));
        }
    }

    /**
     * 将Object对象里面的属性和值转化成Map对象
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map convertToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                log.error(e.getMessage());
            }
            if (value != null) map.put(fieldName, value);

        }
        return map;
    }

    public static Map convertToMap(Object obj,Page page) {
        Map map = convertToMap(obj);
        map.put("page",page);
        return map;
    }

}
